<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-if="dialogVisible" :visible.sync="dialogVisible" :width="lang === 'zh'?'570px':'660px'" top="10vh" @close='close'>
    <div class="dialogContentBoxMaxHeight80">
      <el-form ref="form" :model="record" :label-width="lang === 'zh'?'120px':'205px'" :rules="rules" :key="key" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('类型')" prop="type">
          <el-radio-group v-model="type" @change="typeChange" v-if="!record.id">
            <el-radio label="local" class="local">{{$t('本地认证')}}</el-radio>
            <el-radio label="radius" class="radius">Radius</el-radio>
            <el-radio label="ldap" class="ldap">Ldap</el-radio>
          </el-radio-group>
          <div v-else>{{ type }}</div>
        </el-form-item>
        <!-- 本地认证 -->
        <el-form-item :label="$t('服务器名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="name" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <!-- Radius -->
        <el-form-item :label="$t('地址')" prop="host" v-if="type === 'radius'">
          <el-input v-emoji v-model="record.host" ref="recordHost" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('服务端口')" prop="port" v-if="type === 'radius'" key="portRadius">
          <el-input v-emoji v-model="record.port" ref="recordPort" style="width:280px;" size="small" :placeholder="$t('1-65535,默认:1812')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('共享秘钥')" prop="ssecret" v-if="type === 'radius'">
          <el-input v-emoji v-model="record.ssecret" ref="recordSsecret" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('认证方式')" prop="amode" v-if="type === 'radius'">
          <el-select v-model="record.amode" filterable size='small' style="width:280px;" ref="amodes">
            <el-option v-for="item in amodeList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('失效时间')" prop="tout" v-if="type === 'radius'">
          <el-input v-emoji v-model="record.tout" ref="recordTout" style="width:280px;" size="small" :placeholder="$t('1-180秒,默认为5秒')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('重复认证次数')" prop="rtimes" v-if="type === 'radius'">
          <el-input v-emoji v-model="record.rtimes" ref="recordRtimes" style="width:280px;" size="small" :placeholder="$t('1-10次,默认为3次')"></el-input>
        </el-form-item>
        <!-- Ldap -->
        <el-form-item :label="$t('IP地址')" prop="host" v-if="type === 'ldap'">
          <el-input v-emoji v-model="record.host" ref="recordHost" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('服务端口')" prop="port" v-if="type === 'ldap'" key="portLdap">
          <el-input v-emoji v-model="record.port" ref="recordPort" style="width:280px;" size="small" :placeholder="$t('1-65535,默认:389')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('认证方式')" prop="qtype" v-if="type === 'ldap'">
          <el-select v-model="record.qtype" filterable size='small' style="width:280px;" ref="amode">
            <el-option v-for="item in amodeLdapList" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('服务器DN')" prop="qdn" v-if="type === 'ldap'">
          <el-input v-emoji v-model="record.qdn" ref="recordQdn" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('服务查询账号')" prop="qaccount" v-if="type === 'ldap'">
          <el-input v-emoji v-model="record.qaccount" ref="recordQaccount" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('服务查询密码')" prop="qpassword" v-if="type === 'ldap'">
          <el-input v-emoji v-model="record.qpassword" ref="recordQpassword" style="width:280px;" size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('唯一用户DN')" prop="udn" v-if="type === 'ldap'">
          <el-input v-emoji v-model="record.udn" ref="recordUdn" style="width:280px;" :placeholder="$t('例如:openladp:dc=vpn,dc=com')" size="small"></el-input>
          <el-button type="primary" size="mini" @click="searchClick" class="searchClick">{{$t('查询')}}</el-button>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
    <search-dialog v-if="searchDialogVisible" @getInfoRefresh='getInfoRefresh' ref="refSearchDialogVisible"></search-dialog>
  </el-dialog>
</template>
<script>
import { addLdapInfo, addRadiusInfo, addLocalInfo, editLdapInfo, editRadiusInfo, editLocalInfo, getLdapInfo, getRadiusInfo, getLocalInfo } from '@/api/user/server'
import SearchDialog from './SearchDialog.vue'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  components: { SearchDialog },
  name: 'ServerDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else {
        callback()
      }
    }
    var validatePort = (rule, value, callback) => {
      // if (this.type === 'ldap' && String(value).trim() === '') {
      //   callback(new Error(this.$t('不能为空')))
      // } else
      if (value === '') {
        callback()
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (value !== '' && (Number(value) < 1 || Number(value) > 65535)) {
        callback(new Error(this.$t('端口范围为1-65535')))
      } else {
        callback()
      }
    }
    var validateIp = (rule, value, callback) => {
      let ipv4 = /^((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})(\.((2(5[0-5]|[0-4]\d))|[0-1]?\d{1,2})){3}$/
      let ipv6 = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
      if (String(value).trim() === '') {
        callback(new Error(this.$t('不能为空')))
      } else if (!(ipv4.test(value) || ipv6.test(value))) {
        callback(new Error(this.$t('请输入正确的ip地址')))
      } else {
        callback()
      }
    }
    var validateTout = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (value !== '' && (Number(value) < 1 || Number(value) > 180)) {
        callback(new Error(this.$t('范围为1-180秒')))
      } else {
        callback()
      }
    }
    var validateRtimes = (rule, value, callback) => {
      if (value === '') {
        callback()
      } else if (!this.isInteger(value)) {
        callback(new Error(this.$t('只能输入整数')))
      } else if (value !== '' && (Number(value) < 1 || Number(value) > 10)) {
        callback(new Error(this.$t('范围为1-10次')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      searchDialogVisible: false,
      type: 'local',
      record: {
        id: null,
        name: '',
        host: '',
        ssecret: '',
        amode: '',
        port: '',
        tout: '',
        rtimes: '',
        qtype: '',
        qdn: '',
        qaccount: '',
        qpassword: '',
        udn: ''
      },
      recordCopy: {
        id: null,
        name: '',
        host: '',
        ssecret: '',
        amode: '',
        port: '',
        tout: '',
        rtimes: '',
        qtype: '',
        qdn: '',
        qaccount: '',
        qpassword: '',
        udn: ''
      },
      lang: this.$i18n.locale,
      amodeList: ['pap', 'chap'],
      amodeLdapList: ['openldap'],
      key: '1',
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        ssecret: [{ required: false, validator: validateName, trigger: 'blur' }],
        port: [{ required: false, validator: validatePort, trigger: 'blur' }],
        amode: [{ required: false, validator: validateName, trigger: 'blur' }],
        host: [{ required: false, validator: validateIp, trigger: 'blur' }],
        tout: [{ required: false, validator: validateTout, trigger: 'blur' }],
        rtimes: [{ required: false, validator: validateRtimes, trigger: 'blur' }],
        qdn: [{ required: false, validator: validateName, trigger: 'blur' }],
        qaccount: [{ required: false, validator: validateName, trigger: 'blur' }],
        qpassword: [{ required: false, validator: validateName, trigger: 'blur' }],
        udn: [{ required: false, validator: validateName, trigger: 'blur' }],
        qtype: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  watch: {
    'type' (val) {
      if (val === 'radius') {
        this.$nextTick(() => {
          const data = ['recordSsecret', 'recordHost', 'recordPort', 'recordTout', 'recordRtimes']
          const selectData = ['amodes']
          inputClass(this.$refs, data)
          selectClass(this.$refs, selectData)
        })
      } else if (val === 'ldap') {
        this.$nextTick(() => {
          const data = ['recordPort', 'recordQdn', 'recordHost', 'recordQaccount', 'recordQpassword', 'recordUdn']
          const selectData = ['amode']
          inputClass(this.$refs, data)
          selectClass(this.$refs, selectData)
        })
      }
    }
  },
  methods: {
    init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['name']
        inputClass(this.$refs, data)
      })
      if (data) {
        switch (data.type) {
          case 'radius':
            // this.$nextTick(() => {
            //   const data = ['recordHost', 'recordPort', 'recordSsecret', 'recordTout', 'recordRtimes']
            //   const selectData = ['amodes']
            //   inputClass(this.$refs, data)
            //   selectClass(this.$refs, selectData)
            // })
            getRadiusInfo({ name: data.name }).then(res => {
              if (res.status === 0) {
                this.record = res.info[0]
              }
            })
            break
          case 'ldap':
            getLdapInfo({ name: data.name }).then(res => {
              if (res.status === 0) {
                this.record = res.info[0]
              }
            })
            break
          case 'local':
            getLocalInfo({ name: data.name }).then(res => {
              if (res.status === 0) {
                this.record = res.info[0]
              }
            })
            break
        }
        this.type = data.type
      }
    },
    submit () {
      var flag = true
      this.$refs.form.clearValidate()
      this.$refs.form.validateField(['name', 'ssecret', 'port', 'amode', 'host', 'udn', 'tout', 'rtimes'], (valid) => {
        if (valid) {
          flag = false
        }
      })
      if (flag) {
        switch (this.type) {
          case 'local':
            if (this.record.id) {
              editLocalInfo(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addLocalInfo(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
            break
          case 'radius':
            if (this.record.id) {
              editRadiusInfo(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addRadiusInfo(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
            break
          case 'ldap':
            if (this.record.id) {
              editLdapInfo(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            } else {
              addLdapInfo(this.record).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$parent.listData()
                }
              })
            }
            break
          default:
            break
        }
      }
    },
    getInfoRefresh (qdn) {
      this.record.udn = qdn
    },
    close () {
      this.dialogVisible = false
      this.record = Object.assign({}, this.recordCopy)
      this.type = 'local'
      this.$refs.form.resetFields()
    },
    typeChange (data) {
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.form.clearValidate()
      switch (data) {
        case 'radius':
          this.record.amode = 'pap'
          this.record.qtype = ''
          break
        case 'ldap':
          this.record.qtype = 'openldap'
          this.record.amode = ''
          break
        default:
          this.record.qtype = ''
          this.record.amode = ''
          break
      }
    },
    searchClick () {
      var flag = true
      this.$refs.form.clearValidate()
      this.$refs.form.validateField(['qdn', 'qaccount', 'qpassword', 'host', 'port'], (valid) => {
        if (valid) {
          flag = false
        }
      })
      if (flag) {
        this.searchDialogVisible = true
        this.$nextTick(() => {
          this.$refs.refSearchDialogVisible.init({ host: this.record.host, port: this.record.port, qdn: this.record.qdn, qaccount: this.record.qaccount, qpassword: this.record.qpassword })
        })
      }
    },
    isInteger (value) {
      return (!isNaN(value) && (parseInt(value).toString().length === String(Number(value)).length))
    }
  }
}
</script>
